<template>
  <div class="camera">
    <!-- 确保 video 元素有正确的 ref 属性 -->
    <div class="video-container">
      <video ref="video" autoplay></video>
      <!-- 在视频上方放置虚线框 -->
      <div class="guide-box"></div>
    </div>

    <!-- 确保按钮绑定了正确的事件 -->
    <div class="el-upload__tip" style="color: #f56c6c">
      1.正对摄像头.人头在虚线框中间,并占据虚线框
      2.光线均匀，禁止过暗或过曝，禁止过度化妆
      3.脸部不能遮挡并确保图片清晰，正常表情，不能有搞怪动作
      4.禁止在夜间及逆光下取图，人与背景光线要均匀
    </div>
    <el-button type="primary" @click="capturePhoto">拍照</el-button>

    <!-- 确保 canvas 元素有正确的 ref 属性 -->
    <canvas ref="canvas" style="display:none;"></canvas>

    <!-- 确保下载链接元素有正确的 ref 属性 -->
    <a ref="downloadLink" style="display:none;">下载照片</a>
  </div>
</template>

<script lang="ts">
  import { ref, onMounted, nextTick, defineComponent, defineEmits } from 'vue';
  import { inject } from 'vue';
  export default {
    name: 'Camera',
    setup() {
      // const emit = defineEmits<{
      //   (event : 'updateData', blob : Blob) : void;
      // }>();
      const handleBlob = inject<(blob: Blob) => void>('handleBlob');
      const video = ref<HTMLVideoElement | null>(null);
      const canvas = ref<HTMLCanvasElement | null>(null);
      const downloadLink = ref<HTMLAnchorElement | null>(null);
      const show = ref(false);
      const constraints = { video: true };
      const { proxy } = getCurrentInstance() as ComponentInternalInstance;
      // 获取用户媒体流
      const getUserMedia = async () => {
        try {
          const stream = await navigator.mediaDevices.getUserMedia(constraints);
          show.value = true
          console.log('获取视频流成功:', stream);
          if (video.value) {
            video.value.srcObject = stream;
          }
        } catch (error) {
          proxy?.$modal.msgError("请检查相机是否正常连接!");
          show.value = false
          console.error('Error accessing media devices.', error);
        }
      };

      // 拍照并生成下载链接
      const capturePhoto = () => {
        if (show.value == false) {
          proxy?.$modal.msgError("请检查相机是否正常连接!");
          return
        }
        console.log('点击拍照啦');
        nextTick(() => {
          if (video.value && canvas.value && downloadLink.value) {
            console.log('视频流和Canvas可用');
            canvas.value.width = video.value.videoWidth;
            canvas.value.height = video.value.videoHeight;
            const context = canvas.value.getContext('2d');
            if (context) {
              // 绘制视频内容到 canvas，但不绘制虚线框
              context.drawImage(video.value, 0, 0, video.value.videoWidth, video.value.videoHeight);

              // 生成图片
              canvas.value.toBlob((blob) => {
                if (blob) {

                  console.log(blob, '相机组件blod')
                  

                  const file = new File([blob], 'capture.jpg', {
                    type: 'image/jpeg', // 根据实际类型设置
                    lastModified: Date.now()
                  });
                  handleBlob(file)
                  console.log('File 对象:', file)
                  // emit('updateData', blob); // 发送事件和数据
                  const url = URL.createObjectURL(blob);
                  const fileName = `photo_${Date.now()}.jpg`;

                  // 设置下载链接
                  downloadLink.value.href = url;
                  downloadLink.value.download = fileName;
                  downloadLink.value.click();

                  // 释放内存
                  URL.revokeObjectURL(url);
                }
              }, 'image/jpeg');
            }
          } else {
            console.log('video, canvas 或 downloadLink 未正确加载');
          }
        });
      };

      onMounted(() => {
        console.log('video:', video.value);
        console.log('canvas:', canvas.value);
        console.log('downloadLink:', downloadLink.value);
        getUserMedia();
      });

      return {
        video,
        canvas,
        downloadLink,
        capturePhoto,
      };
    },
  };
</script>

<style scoped>
  .camera {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .video-container {
    position: relative;
    display: inline-block;
    max-width: 600px;
    width: 100%;
  }

  video,
  canvas {
    display: block;
    margin: 10px auto;
    width: 100%;
    max-width: 600px;
  }

  /* 设置虚线框样式 */
  .guide-box {
    position: absolute;
    top: 50%;
    left: 50%;
    width: calc(100% - 380px);
    height: calc(100% - 150px);
    transform: translate(-50%, -50%);
    border: 2px dashed red;
    /* 虚线边框 */
  }

  button {
    display: block;
    margin: 20px auto;
    padding: 10px 20px;
  }
</style>
